import config from '@/config.js'
import notificationUtil from '@/utils/notification.js'
import { getToken } from '@/utils/auth.js'

/**
 * 简化版 WebSocket 连接管理器
 */
class WebSocketManager {
  constructor() {
    this.ws = null;
    this.url = '';
    this.reconnectInterval = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 10;
    this.reconnectDelay = 3000;
    this.shouldReconnect = true;
    this.isConnected = false;
    this.clientId = this.generateClientId();
  }

  /**
   * 生成客户端唯一标识
   */
  generateClientId() {
    return 'client_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }

  /**
   * 初始化 WebSocket 连接
   */
  init(url) {
    this.url = url;
    this.shouldReconnect = true;
    this.connect();
  }

  /**
   * 建立 WebSocket 连接
   */
  connect() {
    if (this.isConnected && this.ws) {
      console.log('WebSocket已连接，无需重新连接');
      return;
    }

    if (this.ws) {
      this.close();
    }

    console.log('开始建立WebSocket连接，URL:', this.url);

    try {
      // #ifdef H5
      this.connectH5();
      // #endif

      // #ifdef APP-PLUS
      this.connectApp();
      // #endif

    } catch (error) {
      console.error('WebSocket连接初始化失败:', error);
      this.handleReconnect();
    }
  }

  /**
   * H5环境连接
   */
  connectH5() {
    console.log('H5环境：使用标准WebSocket');
    this.ws = new WebSocket(this.url);

    this.ws.onopen = () => {
      console.log('WebSocket 连接已建立');
      this.handleOpen();
    };

    this.ws.onmessage = (event) => {
      this.handleMessage(event.data);
    };

    this.ws.onclose = () => {
      console.log('WebSocket 连接已关闭');
      this.handleClose();
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket 连接错误:', error);
      this.handleError(error);
    };
  }

  /**
   * App环境连接
   */
  connectApp() {
    console.log('App环境：使用uni.connectSocket');

    this.ws = uni.connectSocket({
      url: this.url,
      success: (res) => {
        console.log('uni.connectSocket调用成功', res);
      },
      fail: (err) => {
        console.error('uni.connectSocket调用失败', err);
        this.handleReconnect();
      }
    });

    // 使用SocketTask的事件监听
    if (this.ws) {
      this.ws.onOpen(() => {
        console.log('WebSocket连接已建立');
        this.handleOpen();
      });

      this.ws.onMessage((res) => {
        this.handleMessage(res.data);
      });

      this.ws.onClose((res) => {
        console.log('WebSocket连接已关闭', res);
        this.handleClose();
      });

      this.ws.onError((res) => {
        console.error('WebSocket连接错误:', res);
        this.handleError(res);
      });
    }
  }

  /**
   * 连接成功处理
   */
  handleOpen() {
    this.isConnected = true;
    this.reconnectAttempts = 0;
    this.sendIdentification();
    uni.$emit('websocket-connected');
  }

  /**
   * 连接关闭处理
   */
  handleClose() {
    this.isConnected = false;
    uni.$emit('websocket-disconnected');
    this.handleReconnect();
  }

  /**
   * 连接错误处理
   */
  handleError(error) {
    this.isConnected = false;
    uni.$emit('websocket-error', error);
    this.handleReconnect();
  }

  /**
   * 发送客户端标识和用户令牌
   */
  sendIdentification() {
    const token = getToken();
    const identification = {
      type: 'identification',
      clientId: this.clientId,
      token: token || null
    };

    this.send(identification);
    console.log('已发送客户端标识');
  }

  /**
   * 统一处理消息
   */
  handleMessage(data) {
    console.log('收到消息:', data);
    try {
      const message = typeof data === 'string' ? JSON.parse(data) : data;
      uni.$emit('websocket-message', message);

      // 处理通知类型消息
      if (message.type === 'notification' || message.notificationType || message.type === 'job') {
        this.handleNotification(message);
      }
    } catch (error) {
      console.error('解析WebSocket消息失败:', error);
    }
  }

  /**
   * 处理通知类型消息
   */
  async handleNotification(message) {
    console.log('处理通知消息:', message);
    try {
      if (notificationUtil && typeof notificationUtil.sendDailyNotification === 'function') {
        await notificationUtil.sendDailyNotification(message);
        console.log('通知发送成功');
      }
    } catch (error) {
      console.error('处理通知消息失败:', error);
      this.fallbackNotification(message);
    }
  }

  /**
   * 备用通知方案
   */
  fallbackNotification(message) {
    // #ifdef APP-PLUS
    try {
      const title = message.title || '新通知';
      const content = message.content || message.body || '您有新的消息';

      uni.createPushMessage({
        title: title,
        content: content,
        payload: message.payload || {},
        success: (res) => {
          console.log('备用通知发送成功:', res);
        },
        fail: (err) => {
          console.error('备用通知发送失败:', err);
        }
      });
    } catch (error) {
      console.error('备用通知也失败了:', error);
    }
    // #endif
  }

  /**
   * 发送消息
   */
  send(data) {
    if (!this.isConnected) {
      console.warn('WebSocket 未连接，无法发送消息');
      return;
    }

    try {
      const message = typeof data === 'string' ? data : JSON.stringify(data);

      // #ifdef H5
      if (this.ws && this.ws.readyState === 1) {
        this.ws.send(message);
      }
      // #endif

      // #ifdef APP-PLUS
      uni.sendSocketMessage({
        data: message,
        success: () => {
          console.log('消息发送成功');
        },
        fail: (err) => {
          console.error('消息发送失败:', err);
          this.handleReconnect();
        }
      });
      // #endif
    } catch (error) {
      console.error('发送消息异常:', error);
    }
  }

  /**
   * 处理重连逻辑
   */
  handleReconnect() {
    if (!this.shouldReconnect) return;

    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('WebSocket 重连次数已达上限');
      uni.$emit('websocket-reconnect-failed');
      return;
    }

    if (this.reconnectInterval) {
      clearTimeout(this.reconnectInterval);
    }

    this.reconnectAttempts++;
    const delay = Math.min(this.reconnectDelay * this.reconnectAttempts, 30000);

    console.log(`WebSocket 将在 ${delay}ms 后尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);

    this.reconnectInterval = setTimeout(() => {
      this.connect();
    }, delay);
  }

  /**
   * 关闭连接
   */
  close() {
    this.shouldReconnect = false;
    this.isConnected = false;

    if (this.reconnectInterval) {
      clearTimeout(this.reconnectInterval);
      this.reconnectInterval = null;
    }

    // #ifdef H5
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    // #endif

    // #ifdef APP-PLUS
    uni.closeSocket();
    // #endif
  }

  /**
   * 获取连接状态
   */
  getStatus() {
    return {
      isConnected: this.isConnected,
      reconnectAttempts: this.reconnectAttempts,
      maxReconnectAttempts: this.maxReconnectAttempts,
      clientId: this.clientId
    };
  }

  /**
   * 检查连接状态并在需要时重新连接
   */
  checkConnection() {
    console.log('检查WebSocket连接状态');
    if (!this.isConnected) {
      console.log('WebSocket未连接，尝试重新连接');
      this.connect();
    } else {
      console.log('WebSocket已连接');
    }
  }
}

export default new WebSocketManager();